<template>
  <div class="applicationSettings p-6">
    <div class="applicationSettingsHeader mb-4">
      <div class="applicationSettingsHeaderTitle text-xl font-bold">应用设置</div>
    </div>
    <ShortcutInput v-model="shortcut" />
    <p>当前快捷键：{{ shortcut }}</p>
    <el-form :model="form" label-width="140px" class="max-w-3xl" v-if="false">
      <el-form-item label="快捷键 1（启动AI助手）">
        <el-input
          v-model="form.shortcut1"
          placeholder="点击后按组合键"
          @keydown="onShortcutKeydown('shortcut1', $event)"
          @blur="onShortcutBlur('shortcut1')"
          readonly
          clearable
        />
      </el-form-item>

      <el-form-item label="快捷键 2（触发截图）">
        <el-input
          v-model="form.shortcut2"
          placeholder="点击后按组合键"
          @keydown="onShortcutKeydown('shortcut2', $event)"
          @blur="onShortcutBlur('shortcut2')"
          readonly
          clearable
        />
      </el-form-item>

      <el-form-item label="快捷键 3（启动录屏）">
        <el-input
          v-model="form.shortcut3"
          placeholder="点击后按组合键"
          @keydown="onShortcutKeydown('shortcut3', $event)"
          @blur="onShortcutBlur('shortcut3')"
          readonly
          clearable
        />
      </el-form-item>

      <el-form-item label="快捷键 4（打开问答）">
        <el-input
          v-model="form.shortcut4"
          placeholder="点击后按组合键"
          @keydown="onShortcutKeydown('shortcut4', $event)"
          @blur="onShortcutBlur('shortcut4')"
          readonly
          clearable
        />
      </el-form-item>

      <el-form-item label="录屏保存路径">
        <div class="flex w-full gap-2">
          <el-input v-model="form.recordingPath" readonly placeholder="请选择保存目录" />
          <el-button type="primary" @click="onPickPath">选择目录</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import applicationSettingsApi from '@/ipcMainApi/modules/applicationSettingsApi'
import ShortcutInput from './ShortcutInput.vue'

const shortcut = ref('')

type FormT = {
  shortcut1: string
  shortcut2: string
  shortcut3: string
  shortcut4: string
  recordingPath: string
}

const form = reactive<FormT>({
  shortcut1: '',
  shortcut2: '',
  shortcut3: '',
  shortcut4: '',
  recordingPath: ''
})

onMounted(async () => {
  const settings = await applicationSettingsApi.getSettings()
  form.shortcut1 = settings?.shortcuts?.shortcut1 || ''
  form.shortcut2 = settings?.shortcuts?.shortcut2 || ''
  form.shortcut3 = settings?.shortcuts?.shortcut3 || ''
  form.shortcut4 = settings?.shortcuts?.shortcut4 || ''
  form.recordingPath = settings?.recordingPath || ''
})

function onShortcutKeydown(key: keyof FormT, e: KeyboardEvent) {
  if (key === 'recordingPath') return
  e.preventDefault()
  e.stopPropagation()

  const parts: string[] = []
  if (e.ctrlKey) parts.push('Ctrl')
  if (e.shiftKey) parts.push('Shift')
  if (e.altKey) parts.push('Alt')
  if (e.metaKey) parts.push('Super')

  const code = e.code || ''
  let main = ''
  if (/^Key[A-Z]$/.test(code)) {
    main = code.replace('Key', '').toUpperCase()
  } else if (/^Digit[0-9]$/.test(code)) {
    main = code.replace('Digit', '')
  } else if (/^F[1-9][0-9]?$/.test(e.key)) {
    main = e.key.toUpperCase()
  } else {
    const k = (e.key || '').toLowerCase()
    const map: Record<string, string> = {
      ' ': 'Space',
      spacebar: 'Space',
      arrowup: 'Up',
      arrowdown: 'Down',
      arrowleft: 'Left',
      arrowright: 'Right',
      escape: 'Esc',
      esc: 'Esc',
      enter: 'Enter',
      tab: 'Tab',
      backspace: 'Backspace',
      delete: 'Delete',
      insert: 'Insert',
      home: 'Home',
      end: 'End',
      pageup: 'PageUp',
      pagedown: 'PageDown'
    }
    main = map[k] || (e.key?.length === 1 ? e.key.toUpperCase() : e.key)
  }

  if (!main) return
  const accel = parts.length ? `${parts.join('+')}+${main}` : main
  ;(form as any)[key] = accel
}

async function onShortcutBlur(key: 'shortcut1' | 'shortcut2' | 'shortcut3' | 'shortcut4') {
  const val = form[key]?.trim() || ''
  // 允许清空：清空即保存为空，表示禁用该快捷键
  const validateRes = await applicationSettingsApi.validateSingleShortcut(key, val)
  if (!validateRes?.ok) {
    const msgs: string[] = []
    if (validateRes?.duplicate) msgs.push('与其他已配置快捷键重复')
    if (validateRes?.conflict) msgs.push('与当前已注册快捷键冲突')
    ElMessage.warning(msgs.join('，') || '快捷键无效或冲突')
    // 清空并不保存该值（改为保存为空，表示禁用）
    ;(form as any)[key] = ''
    await applicationSettingsApi.saveSingleShortcut(key, '')
    return
  }

  // 无冲突：立即保存并应用
  const saveRes = await applicationSettingsApi.saveSingleShortcut(key, val)
  if (saveRes?.success) {
    ElMessage.success('快捷键已保存并生效')
  } else {
    ElMessage.warning(`快捷键保存失败，以下注册失败：${(saveRes?.failed || []).join(', ')}`)
  }
}

async function onPickPath() {
  const p = await applicationSettingsApi.pickRecordingPath()
  if (p) {
    form.recordingPath = p
    const res = await applicationSettingsApi.saveRecordingPath(p)
    if (res?.success) {
      ElMessage.success('录屏保存路径已保存')
    } else {
      ElMessage.error('保存录屏路径失败')
    }
  }
}
</script>

<style lang="scss" scoped>
.applicationSettings {
  background: red;
}
.shortcut-input {
  width: 300px;
}
</style>
